<?php

/**
 * Model standard Registro
 *
 * @author     luigi.pastore (gigi@la-fabbrica.org)
 * @package    Registro
 * @copyright  Copyright (c) 2014 Luigi Pastore
 * @created    16-mag-2014
 */
class Classes_Core_Model
{
    /**
     * Mapping al table model
     */
    protected $_db;
    protected $_result;
    protected $_ret = array( );

    public function __construct( array $data = null )
    {
	// Connessione DB...
	$this->_db = Classes_MySqliLayer::getInstance();

	if( is_array( $data ) )
	{
	    $this->setOptions( $data );
	}
    }

    /*
     *
     */
    public function __call( $name, $arguments )
    {
	if( substr( $name, 0, 3 ) == "set" )
	{
	    return $this->__set( substr( $name, 3 ), $arguments[0] );
	}
	if( substr( $name, 0, 3 ) == "get" )
	{
	    return $this->__get( substr( $name, 3 ) );
	}
	throw new Exception( 'Metodo ' . $name . ' non Supportato' );
    }

    /*
     *
     */

    public function __set( $name, $value )
    {
	$method = 'set' . $name;
	$propertyName = "_" . strtolower( $name );
	if( method_exists( $this, $method ) )
	{
	    method_exists( $this, $method );
	}
	elseif( !property_exists( $this, $propertyName ) )
	{
	    throw new Exception( '(Set)Proprietà invalida: ' . $propertyName );
	}
	elseif( property_exists( $this, $propertyName ) )
	{
	    $this->$propertyName = $value;
	}

	return $this;
    }

    /*
     *
     */

    public function __get( $name )
    {
	$method = 'get' . $name;
	$propertyName = "_" . strtolower( $name );
	if( method_exists( $this, $method ) )
	{
	    return $this->$method();
	}
	elseif( !property_exists( $this, $propertyName ) )
	{
	    throw new Exception( '(Get)Proprietà invalida: ' . $propertyName );
	}
	else
	{
	    return $this->$propertyName;
	}
    }

    public function setOptions( array $options )
    {
	$methods = get_class_methods( $this );
	foreach( $options as $key => $value )
	{
	    $method = 'set' . ucfirst( $key );
	    //if ( in_array( $method, $methods ) )
	    //{
	    $this->$method( $value );
	    //}
	}
	return $this;
    }

    /*
     * Restituisce l'array delle proprietà SETTATE dell'oggetto
     */

    public function toArray()
    {
	$values = array( );
	foreach( get_object_vars( $this ) as $pkey => $pvalue )
	{
	    if( substr( $pkey, 0, 1 ) == "_" && $pkey !== '_db' && isset( $this->$pkey ) )
	    {
		$arrkey = substr( $pkey, 1 );
		$call = "get" . ucfirst( substr( $pkey, 1 ) );
		$values[$arrkey] = $this->$call();
	    }
	}

	return $values;
    }

}
